package com.pai4j.aigc.llm.service;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Service
public class MetricsService {

    @Autowired(required = false)
    private MeterRegistry meterRegistry;

    public void recordSuccess(String provider, String tenantId, String modelCode, long latencyMs) {
        if (meterRegistry == null) return;

        meterRegistry.counter("llm_requests_total",
                "provider", nullToNA(provider),
                "tenant", nullToNA(tenantId),
                "model", nullToNA(modelCode),
                "success", "true"
        ).increment();

        Timer.builder("llm_latency_ms")
                .tag("provider", nullToNA(provider))
                .tag("tenant", nullToNA(tenantId))
                .tag("model", nullToNA(modelCode))
                .register(meterRegistry)
                .record(latencyMs, TimeUnit.MILLISECONDS);
    }

    public void recordFailure(String provider, String tenantId, String modelCode, long latencyMs) {
        if (meterRegistry == null) return;

        meterRegistry.counter("llm_requests_total",
                "provider", nullToNA(provider),
                "tenant", nullToNA(tenantId),
                "model", nullToNA(modelCode),
                "success", "false"
        ).increment();

        Timer.builder("llm_latency_ms")
                .tag("provider", nullToNA(provider))
                .tag("tenant", nullToNA(tenantId))
                .tag("model", nullToNA(modelCode))
                .register(meterRegistry)
                .record(latencyMs, TimeUnit.MILLISECONDS);
    }


    private String nullToNA(String v) { return v == null ? "NA" : v; }
}
